<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Album;
use App\Models\AlbumType;
use App\Models\AlbumImage;
use App\Models\Activity;
use App\Models\AwardLevel;
use App\Models\AwardSet;
use App\Models\AwardType;
use App\Models\AwardTypeActivity;
use App\Models\GameType;
use App\Models\GameTypeActivity;
use App\Models\Participant;
use App\Models\ParticipantActivity;
use App\Models\Survey;
use App\Org\Developer\Helper;
use App\Org\Developer\JsonReturnInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * @author 陈玉琦
 * 活动（游戏、抽奖、大屏幕）
 */
class ActivityController extends Controller
{
    private $fields = ['id', 'user_id', 'type', 'title', 'bg_image_url', 'game_bg_url', 'start_time', 'end_time'];

    /**
     * 显示活动
     * 用户的所有活动，或者某一期活动
     *
     * 我的“传播”---显示用户制作过的场景列表，受访人数（PV）。
     *      如果该H5添加过表单，提供表单数据下载（哪些人填写了参加活动的表单）。
     * 我的“活动”---显示用户添加过的活动列表，受访人数【下载数据--此功能单独处理】。
     *
     * @return array
     */
    public function index(Request $request)
    {
        // 此接口返回用户所有的活动、调查投票和问卷等列表数据
        if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            // \App\Org\Developer\Helper::log('222');
            // 获取用户的所有活动
            // ['id', 'user_id', 'game_id', 'title', 'bg_image_url', 'counts', 'start_time', 'end_time']
            $activityData = Activity::select(['id', 'title', 'type', 'bg_image_url', 'game_bg_url', 'created_at'])
                ->where(['user_id' => $user_id])->get();

            // 游戏类型数据
            $gameTypeData = GameType::select(['id', 'title'])->get();

            // 抽奖类型数据
            $awardTypeData = AwardType::select(['id', 'title'])->get();

            // 抽奖奖品等级数据
            $awardLevelData = AwardLevel::select(['id', 'title'])->where('id', '>', 1)->get();

            // 相册类型数据
            $albumTypeData = AlbumType::select(['id', 'title'])->get();

            // 活动的大屏幕相册的第一张图片
            foreach ($activityData as $key => $val) {
                $activity_id = $val['id'];
                if ($val['type'] == 'screen') {
                    $data = AlbumImage::select(['album_images.album_id', 'album_images.image_url', 'albums.album_type_id'])
                        ->join('albums', function ($join) {
                            $join->on('albums.id', '=', 'album_images.album_id');
                        })
                        ->where('album_images.album_id', function ($query) use ($activity_id) {
                            $query->select('id')->from('albums')->where(['activity_id' => $activity_id]);
                        })
                        ->first();

                    if (isset($data) && !empty($data)) {
                        $activityData[$key]['album_id'] = $data['album_id'];
                        $activityData[$key]['image_url'] = $data['image_url'];
                        $activityData[$key]['album_type_id'] = $data['album_type_id'];
                    }
                } else if ($val['type'] == 'game') {
                    $data = GameTypeActivity::select(['id', 'type_id', 'game_id'])
                        ->where(['activity_id' => $activity_id])
                        ->first();
                    if (isset($data) && !empty($data)) {
                        $activityData[$key]['game_type_id'] = $data['type_id'];
                        $activityData[$key]['game_id'] = $data['game_id'];
                    }
                } else if ($val['type'] == 'award') {
                    $data = AwardTypeActivity::select(['id', 'type_id', 'award_id'])
                        ->where(['activity_id' => $activity_id])
                        ->first();
                    if (isset($data) && !empty($data)) {
                        $activityData[$key]['award_type_id'] = $data['type_id'];
                        $activityData[$key]['award_id'] = $data['game_id'];
                    }
                }
            }

            // 获取用户的所有调查投票
            $voteData = Survey::select(['id', 'title', 'illustration', 'qrcode_image_url', 'created_at'])
                ->where(['user_id' => $user_id, 'type' => 'vote'])->get()->all();

            // 获取用户的所有调查问卷
            $questionnaireData = Survey::select(['id', 'title', 'illustration', 'qrcode_image_url', 'created_at'])
                ->where(['user_id' => $user_id, 'type' => 'questionnaire'])->get();

            return JsonReturnInfo::infoSuccess('获取数据成功.', [
                'acitivity_data' => $activityData,
                'game_type' => $gameTypeData,
                'award_type' => $awardTypeData,
                'award_level' => $awardLevelData,
                'album_type' => $albumTypeData,
                'vote_data' => $voteData,
                'questionnaire_data' => $questionnaireData,
            ]);
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * 添加一个活动
     * 传过来的数据有：活动标题，背景图片，
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function store(Request $request)
    {
        // 用户 user_id
        if (Helper::idInvalid($activityData['user_id'] = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 活动的标题
        if (empty($activityData['title'] = $request->input('title', ''))) {
            return JsonReturnInfo::infoEmpty('title');
        }

        // 活动类型
        if (empty($activityData['type'] = $request->input('type', ''))) {
            return JsonReturnInfo::infoEmpty('type');
        }

        // 游戏类型 game_type_id
        if (Helper::idInvalid($type_id = $request->input('type_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 生成二维码需要的前缀
        if (empty($qrcode_prefix = $request->input('qrcode_prefix', ''))) {
            return JsonReturnInfo::infoEmpty('qrcode_prefix');
        }

        // 开始时间和结束时间
        $activityData['start_time'] = $request->input('start_time', '');
        $activityData['end_time'] = $request->input('end_time', '');
        if (empty($activityData['start_time']) || empty($activityData['end_time'])) {
            return JsonReturnInfo::infoEmpty('start_time 或 end_time');
        }
        // 开始时间必须早于结束时间
        if ($activityData['start_time'] >= $activityData['end_time']) {
            return JsonReturnInfo::START_TIME_GET_END_TIME_ERROR;
        }
        $activityData['start_time'] = date('Y-m-d H:i:s', intval($activityData['start_time'] / 1000) - 8 * 3600);
        $activityData['end_time'] = date('Y-m-d H:i:s', intval($activityData['end_time'] / 1000) - 8 * 3600);

        // 活动背景图片，非必须
        $activityData['bg_image_url'] = $request->input('bg_image_url', '');

        // 游戏（打飞机）时，可以设置游戏背景图片，非必须
        $activityData['game_bg_url'] = $request->input('game_bg_url', '');

        try {
            $activity_id = 0;

            // 一个用户可以创建重复的活动，比如关于 xxx 的投票，所以不必进行重复性校验。
            // 可以直接写入活动信息
            $createModel = Activity::create($activityData);
            if (isset($createModel) && ($activity_id = $createModel->id)) {
                if ($activityData['type'] == 'game') {
                    // 写入 game_type_activities 表
                    $gameTypeActivityModel = GameTypeActivity::create([
                        'activity_id' => $activity_id,
                        'type_id' => $type_id
                    ]);
                    if (!(isset($gameTypeActivityModel) && $gameTypeActivityModel->id)) {
                        return JsonReturnInfo::infoFailure('活动创建失败.');
                    }
                } else if ($activityData['type'] == 'award') {
                    // 写入 award_type_activities 表
                    $awardTypeActivityModel = AwardTypeActivity::create([
                        'activity_id' => $activity_id,
                        'type_id' => $type_id
                    ]);

                    if (!(isset($awardTypeActivityModel) && $awardTypeActivityModel->id)) {
                        return JsonReturnInfo::infoFailure('活动创建失败.');
                    }

                    // 奖品内容
                    if (empty($content = $request->input('content', ''))) {
                        return JsonReturnInfo::infoEmpty('content');
                    }

                    // content:[{level_id:2,title:'奖品名称',total:xx}, {level_id:3,title:'奖品名称',total:xx}, {level_id:4,title:'奖品名称',total:xx}]
                    $contentArray = json_decode($content, true);
                    if (empty($contentArray)) {//  || (count($contentArray) > 3)
                        return JsonReturnInfo::infoFailure('奖品分类不能为空.');//  或者超过 3 个
                    }
                    $batch = [];
                    foreach ($contentArray as $val) {
                        if ($val['total'] <= 0) {
                            return JsonReturnInfo::infoFailure('奖品数量必须是大于 0 的正整数.');
                        }
                        if (Helper::idInvalid($val['level_id'])) {
                            return JsonReturnInfo::infoFailure('奖品等级 id 必须是大于 0 的正整数.');
                        }
                        $batch[] = [
                            'activity_id' => $activity_id,
                            'level_id' => $val['level_id'],
                            'title' => $val['title'],
                            'total' => $val['total'],
                            'surplus' => $val['total']
                        ];
                    }

                    $result = AwardSet::insert($batch);
                    if (!$result) {
                        return JsonReturnInfo::infoFailure('奖品设置失败.');
                    }
                }

                // 需要生成二维码图片，将路径返回给 node
                $qrcodeImagePath = \App\Org\Developer\Helper::makeQrcodeImage($qrcode_prefix . $activity_id);

                $createModel->qrcode_image_url = $qrcodeImagePath;
                $result = $createModel->save();
                if (!$result) {
                    return JsonReturnInfo::infoFailure('活动创建失败.');
                }

                return JsonReturnInfo::infoSuccess('活动创建成功.', ['activity_id' => $activity_id, 'qrcode_image' => $qrcodeImagePath]);
            }
            return JsonReturnInfo::infoFailure('活动创建失败.');
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 修改活动
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id 活动 activity_id
     * @return array
     */
    public function update(Request $request, $id)
    {
        // 活动 activity_id 是否合法
        if (Helper::idInvalid($id)) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 用户 user_id
        if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 活动类型
        if (empty($activityData['type'] = $request->input('type', ''))) {
            return JsonReturnInfo::infoEmpty('type');
        }

        // 游戏类型 game_type_id
        if (Helper::idInvalid($type_id = $request->input('type_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 活动的标题
        if (empty($activityData['title'] = $request->input('title', ''))) {
            return JsonReturnInfo::infoEmpty('title');
        }

        // 开始时间和结束时间
        $activityData['start_time'] = $request->input('start_time', '');
        $activityData['end_time'] = $request->input('end_time', '');
        if (empty($activityData['start_time']) || empty($activityData['end_time'])) {
            return JsonReturnInfo::infoEmpty('start_time 或 end_time');
        }
        // 开始时间必须早于结束时间
        if ($activityData['start_time'] >= $activityData['end_time']) {
            return JsonReturnInfo::START_TIME_GET_END_TIME_ERROR;
        }
        $activityData['start_time'] = date('Y-m-d H:i:s', intval($activityData['start_time'] / 1000) - 8 * 3600);
        $activityData['end_time'] = date('Y-m-d H:i:s', intval($activityData['end_time'] / 1000) - 8 * 3600);

        // 活动背景图片，必须
        $activityData['bg_image_url'] = $request->input('bg_image_url', '');

        // 游戏（打飞机）时，可以设置游戏背景图片，非必须
        $activityData['game_bg_url'] = $request->input('game_bg_url', '');

        try {
            // 必须存在且必须是用户自己的资源
            $activityModel = Activity::select($this->fields)->where(['id' => $id])->first();
            if (!(isset($activityModel) && $activityModel->id)) {
                return JsonReturnInfo::infoFailure('要修改的活动不存在.');
            }
            if (!Helper::isUserSelfResource($user_id, $activityModel->user_id)) {
                return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
            }

            $activityModel->title = $activityData['title'];
            $activityModel->type = $activityData['type'];
            $activityModel->start_time = $activityData['start_time'];
            $activityModel->end_time = $activityData['end_time'];
            $activityModel->bg_image_url = $activityData['bg_image_url'];
            $activityModel->game_bg_url = $activityData['game_bg_url'];

            $result = $activityModel->save();
            if (!$result) {
                return JsonReturnInfo::infoFailure('活动修改失败.');
            }

            // 游戏
            if ($activityData['type'] == 'game') {
                // 修改 game_type_activities 表
                $gameTypeActivityModel = GameTypeActivity::where(['activity_id' => $id])->first();
                if (isset($gameTypeActivityModel) && $gameTypeActivityModel->id) {
                    $gameTypeActivityModel->type_id = $type_id;
                    $result = $gameTypeActivityModel->save();
                    if (!$result) {
                        return JsonReturnInfo::infoFailure('活动修改失败.');
                    }
                } else {
                    // 写入 game_type_activities 表
                    $gameTypeActivityModel = GameTypeActivity::create([
                        'activity_id' => $id,
                        'type_id' => $type_id
                    ]);
                    if (!(isset($gameTypeActivityModel) && $gameTypeActivityModel->id)) {
                        return JsonReturnInfo::infoFailure('活动修改失败.game_type_activities 写入失败.');
                    }
                }
            }
            // 抽奖
            else if ($activityData['type'] == 'award') {
                // 奖品内容
                if (empty($content = $request->input('content', ''))) {
                    return JsonReturnInfo::infoEmpty('content');
                }

                // content:[{"award_set_id": 1,title:'奖品名称', level_id:2,total:xx}, {"award_set_id": 2,title:'奖品名称', level_id:3,total:xx}, {"award_set_id": 3,title:'奖品名称', level_id:4,total:xx}]
                $contentArray = json_decode($content, true);
                if (empty($contentArray)) {//  || (count($contentArray) > 3)
                    return JsonReturnInfo::infoFailure('奖品分类不能为空.');// 或者超过 3 个
                }
                foreach ($contentArray as $val) {
                    if ($val['total'] <= 0) {
                        return JsonReturnInfo::infoFailure('奖品数量必须是大于 0 的正整数.');
                    }
                    if (Helper::idInvalid($val['level_id'])) {
                        return JsonReturnInfo::infoFailure('奖品等级 id 必须是大于 0 的正整数.');
                    }
                    AwardSet::where(['id' => $val['award_set_id']])->update([
                        'level_id' => $val['level_id'],
                        'title' => $val['title'],
                        'total' => $val['total'],
                        'surplus' => $val['total']
                    ]);
                    // 个别的可能没有修改，无法判断 $result (值可能是 0)
                }

                // 修改 award_type_activities 表
                $awardTypeActivityModel = AwardTypeActivity::where(['activity_id' => $id])->first();
                if (isset($awardTypeActivityModel) && $awardTypeActivityModel->id) {
                    $awardTypeActivityModel->type_id = $type_id;
                    $result = $awardTypeActivityModel->save();
                    if (!$result) {
                        return JsonReturnInfo::infoFailure('活动修改失败.');
                    }
                } else {
                    // 写入 award_type_activities 表
                    $awardTypeActivityModel = AwardTypeActivity::create([
                        'activity_id' => $id,
                        'type_id' => $type_id
                    ]);
                    if (!(isset($awardTypeActivityModel) && $awardTypeActivityModel->id)) {
                        return JsonReturnInfo::infoFailure('活动修改失败.award_type_activities 写入失败.');
                    }
                }
            }
            return JsonReturnInfo::infoSuccess('活动修改成功.');
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * 删除一个活动
     *
     * @param  int $id 活动 activity_id
     * @return array
     */
    public function destroy(Request $request, $id)
    {
        // 活动 activity_id 和用户 user_id 是否合法
        if (Helper::idInvalid($id) || Helper::idInvalid($user_id = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            // 必须存在且必须是自己的资源
            $activityModel = Activity::select($this->fields)->find($id);
            if (!(isset($activityModel) && $activityModel->id)) {
                return JsonReturnInfo::infoFailure('要删除的活动不存在.');
            }
            if (!Helper::isUserSelfResource($user_id, $activityModel->user_id)) {
                return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
            }

            // 删除可能存在的相关数据（不保证一定会有相关数据）
            if ($activityModel == 'game') {
                GameTypeActivity::where(['activity_id' => $id])->delete();
            } else if ($activityModel == 'award') {
                AwardTypeActivity::where(['activity_id' => $id])->delete();
            } else if ($activityModel == 'screen') {
                Album::where(['activity_id' => $id])->delete();
            }

            // 删除
            $result = $activityModel->delete();
            if ($result) {
                return JsonReturnInfo::infoSuccess('活动删除成功.');
            }
            return JsonReturnInfo::infoFailure('活动删除失败.');
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * 参与者的游戏成绩
     *
     * @return array
     */
    public function reply(Request $request)
    {
        // 活动参与者 participant_id
        //if (Helper::idInvalid($participant_id = $request->input('participant_id', 0))) {
        //    return JsonReturnInfo::ID_ERROR;
        //}

        if (empty($openid = $request->input('openid', ''))) {
            return JsonReturnInfo::infoEmpty('openid');
        }

        // 活动 activity_id
        // 可以根据该值查询活动类型。如果没有传递该值，则需要传递活动类型，倒不如传递该值。
        if (Helper::idInvalid($activity_id = $request->input('activity_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            // $participant_id 是否存在
            // $participantModel = Participant::select(['id'])->where(['id' => $participant_id])->first();
            // if (!(isset($participantModel) && $participantModel->id)) {
            //     return JsonReturnInfo::infoFailure('participant_id 错误，参与者不存在.');
            // }

            // 活动记录
            $activityModel = Activity::select($this->fields)->where(['id' => $activity_id])->first();
            if (!(isset($activityModel) && $activityModel->id)) {
                return JsonReturnInfo::infoFailure('该活动不存在.');
            }

            // 反馈结果不能为空
            if (empty($result = $request->input('result', ''))) {
                return JsonReturnInfo::infoEmpty('result');
            }

            // 成绩按数字计算
            if (intval($result) < 0) {
                return JsonReturnInfo::LESS_THEN_ZERO_ERROR;
            }

            // 根据 openid 查询参与者的 participant_id
            $participant_id = Participant::where(['openid' => $openid])->value('id');
            if (!isset($participant_id) || empty($participant_id)) {
                return JsonReturnInfo::infoFailure('openid 错误，此参与者不存在.');
            }

            $condition['participant_id'] = $participant_id;
            $condition['activity_id'] = $activity_id;

            $updateModel = ParticipantActivity::where($condition)->first();
            if (!(isset($updateModel) && $updateModel->participant_id)) {
                return JsonReturnInfo::infoFailure('未参与过该活动，无法写入成绩.');
            }

            // 如果已有成绩，比较大小，保留最大的
            if ($updateModel->score) {
                $result = ($updateModel->score > intval($result)) ? $updateModel->score : intval($result);
            }

            $updateModel->score = intval($result);
            // 更新
            $res = $updateModel->save();
            if ($res) {
                return JsonReturnInfo::infoSuccess('成绩写入成功.');
            } else {
                return JsonReturnInfo::infoFailure('成绩写入失败.');
            }
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    // 游戏，分数最高的十个人
    public function scoreTop(Request $request)
    {
        // 必须的用户 user_id
        //if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
        //    return JsonReturnInfo::ID_ERROR;
        //}

        // 活动 activity_id
        if (Helper::idInvalid($activity_id = $request->input('activity_id'))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 前 n 名
        if (Helper::idInvalid($num = $request->input('num', 10))) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            // 必须存在且必须是用户自己的资源
            $activityModel = Activity::select($this->fields)->where(['id' => $activity_id])->first();
            if (!(isset($activityModel) && $activityModel->id)) {
                return JsonReturnInfo::infoFailure('指定活动不存在.');
            }
            //if (!Helper::isUserSelfResource($user_id, $activityModel->user_id)) {
            //    return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
            //}

            $sql = "SELECT t.activity_id,a.title,a.type,p.nickname,p.headimgurl,t.score FROM 
(SELECT participant_id,score,activity_id FROM thearte_participant_activities WHERE activity_id={$activity_id} AND deleted_at IS NULL ORDER BY score DESC,participant_id ASC) AS t 
LEFT JOIN thearte_participants p ON p.id=t.participant_id 
LEFT JOIN thearte_activities a ON a.id=t.activity_id LIMIT " . $num;
            $result = \Illuminate\Support\Facades\DB::select($sql);

            // foreach ($result as $key => $val) {
            //     $result[$key]->nickname = urldecode($val->nickname);
            // }

            /*
            $activityArray = [];
            foreach ($result as $val) {
                $val = json_decode(json_encode($val), true);
                $activity_id = $val['activity_id'];
                $activity_title = $val['title'];
                unset($val['activity_id'], $val['title']);
                if (isset($activityArray[$activity_id]['child'])) {
                    $activityArray[$activity_id]['child'][] = $val;
                } else {
                    $activityArray[$activity_id] = [
                        'activity_id' => $activity_id,
                        'activity_title' => $activity_title,
                        'child' => [$val]
                    ];
                }
            }
            */

            $activityModel = Activity::select(['title', 'bg_image_url', 'qrcode_image_url'])->where(['id' => $activity_id])->first();

            return JsonReturnInfo::infoSuccess('获取数据成功', [
                'data' => $result, // array_values($activityArray),
                'title' => $activityModel['title'],
                'qrcode_image_url' => $activityModel['qrcode_image_url'],
                'bg_image_url' => $activityModel['bg_image_url']
            ]);
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * 游戏结果下载
     * 按成绩倒序
     */
    public function download(Request $request)
    {
        // 用户 user_id
        if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 活动 activity_id
        if (Helper::idInvalid($activity_id = $request->input('activity_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 必须是用户自己的资源
        $activityModel = Activity::select($this->fields)->where(['id' => $activity_id])->first();
        if (!(isset($activityModel) && $activityModel->id)) {
            return JsonReturnInfo::infoFailure('要下载的游戏不存在.');
        }
        if (!Helper::isUserSelfResource($user_id, $activityModel->user_id)) {
            return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
        }

        $sql = "SELECT p.nickname,pa.score FROM thearte_participant_activities AS pa LEFT JOIN thearte_participants p ON p.id = pa.participant_id WHERE pa.activity_id={$activity_id} AND pa.deleted_at IS NULL ORDER BY pa.score DESC,pa.id ASC";

        $data = \Illuminate\Support\Facades\DB::select($sql); // 结果中每个元素都是一个 stdClass 对象。

        foreach ($data as $k => $item) {
            $item->nickname = urldecode($item->nickname);
            $data[$k] = json_decode(json_encode($item), true);
        }

        $title = [
            'username' => '参与者微信昵称',
            'score' => '成绩'
        ];
        Helper::downloadExcel($data, $title, $activityModel->title, ['nickname']);// DateHelper::dateTimeName()
    }

    /**
     * 样例模式参与者报名表
     * 开始时以为也是 activities 表中的，后来发现，其实是参加一个剧本
     */
    public function downloadExample(Request $request)
    {
        // 用户 user_id
        // if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
        //     return JsonReturnInfo::ID_ERROR;
        // }

        // 剧本 play_id
        if (Helper::idInvalid($play_id = $request->input('play_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 必须是用户自己的资源
        $playModel = \App\Models\Play::select(['id', 'user_id', 'title'])->where(['id' => $play_id])->first();
        if (!(isset($playModel) && $playModel->id)) {
            return JsonReturnInfo::infoFailure('要下载的剧本不存在.');
        }
        // if (!Helper::isUserSelfResource($user_id, $playModel->user_id)) {
        //     return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
        // }

        $sql = "SELECT p.username,p.mobile FROM thearte_participant_activities AS pa LEFT JOIN thearte_participants p ON p.id = pa.participant_id WHERE pa.play_id={$play_id}";

        $data = \Illuminate\Support\Facades\DB::select($sql); // 结果中每个元素都是一个 stdClass 对象。

        foreach ($data as $k => $item) {
            $data[$k] = json_decode(json_encode($item), true);
        }

        $title = [
            'username' => '参与者姓名',
            'mobile' => '手机号码'
        ];
        Helper::downloadExcel($data, $title, $playModel->title);// DateHelper::dateTimeName()
    }
}
